package drds.common.db.sql_mapping.dynamic_tag.tag;


import drds.common.db.sql_mapping.dynamic_tag.tag_context.TagContext;
import drds.common.db.sql_mapping.dynamic_tag.token_handler.TokenHandler;
import drds.common.db.sql_mapping.dynamic_tag.token_handler.TokenParser;
import drds.common.db.sql_mapping.dynamic_tag.token_handler.VariableReplacementCheckTokenHandler;
import drds.common.db.sql_mapping.dynamic_tag.token_handler.VariableReplacementTokenParser;


public class VariableReplacementTextTag implements Tag {
    private final String text;

    public VariableReplacementTextTag(String text) {
        this.text = text;
    }

    /**
     * 判断是否含有${}token
     */
    public boolean isHasToken() {
        VariableReplacementCheckTokenHandler variableReplacementCheckTokenHandler = new VariableReplacementCheckTokenHandler();
        TokenParser tokenParser = createTokenParser(variableReplacementCheckTokenHandler);
        tokenParser.parse(text);
        return variableReplacementCheckTokenHandler.isHasToken();
    }

    @Override
    public boolean apply(TagContext tagContext) {
        TokenParser tokenParser = createTokenParser(new VariableReplacementTokenParser(tagContext));
        tagContext.sqlAppend(tokenParser.parse(text));
        return true;
    }

    /**
     * 只针对${}
     */
    private TokenParser createTokenParser(TokenHandler tokenHandler) {
        return new TokenParser("${", "}", tokenHandler);
    }

}
